package com.peng.leetcode.greedy;

/**
 * MaxProfit
 *
 * @author: lupeng6
 * @create: 2020/12/16 15:00
 */
public class MaxProfit {

    public static void main(String[] args) {
        int[] arr = {7,1,5,3,6,4};
        int i = new Solution1().maxProfit(arr);
        System.out.println(i);
    }

    static class Solution {
        public int maxProfit(int[] prices) {
            if (prices.length <= 1) {
                return 0;
            }
            int sum = 0;
            for (int i = 1; i < prices.length; i++) {
                if (prices[i - 1] < prices[i]) {
                    sum += prices[i] - prices[i - 1];
                }
            }
            return sum;
        }
    }

    /**
     * 121. 买卖股票的最佳时机
     *
     * @author lupeng6
     * @date 2021/1/20 22:15
     */
    static class Solution1 {
        public int maxProfit(int[] prices) {
            if (prices.length <= 1) {
                return 0;
            }
            int minPrice = Integer.MAX_VALUE;
            int maxProfit = 0;
            for (int i = 0; i < prices.length; i++) {
                int price = prices[i];
                if (price < minPrice) {
                    minPrice = price;
                } else if (price - minPrice > maxProfit) {
                    maxProfit = price - minPrice;
                }
            }
            return maxProfit;
        }
    }


}
